import subprocess
import time
import os

class AutoArchieveClass:

    def __init__(self):
        self.__BUILDPATH = '/ArchieveFiles'

    # 从git上拉取最新的代码
    def updateProjectFromGitWith(self, path):
        cmd1 = 'cd ' + path + ';' + 'git pull'
        gitPullResult = subprocess.call(cmd1, shell=True)
        if gitPullResult == 0:
            print('已从git上拉取最新代码')
        else:
            print('git pull 失败')
            exit()

    # 更新pod
    def updatePods(self, path):
        cmd1 = 'cd ' + path + ';' + 'pod install'
        podPullResult = subprocess.call(cmd1, shell=True)
        if podPullResult == 0:
            print('cocoapods 已更新')
        else:
            print('pod install 失败')
            exit()

    # archieve
    def __archieveProject(self, xcworkspace, path, type=0):
        config = 'Release'
        if type == 0:
            config = 'Debug'
        elif type == 1:
            config = 'Release'
        archieveName = xcworkspace + self.__dateStr()
        cmd1 = 'cd ' + path + ';'
        if not os.path.exists(self.__BUILDPATH):
            subprocess.call('mkdir '+self.__BUILDPATH, shell=True)
        archievePath = os.getcwd()+self.__BUILDPATH +'/'+ archieveName + '.xcarchive'
        cmd2 = 'xcodebuild -workspace ' + xcworkspace + '.xcworkspace -scheme ' + xcworkspace + ' -configuration ' + config + ' -archivePath ' + archievePath+' archive'
        cmd = cmd1 + cmd2
        subprocess.call(cmd, shell=True)
        return archievePath

    def buildProject(self, path, name, type=0):
        archievePath = self.__archieveProject(name, path, type)
        buildPath = os.getcwd()+self.__BUILDPATH+'/build'
        if not os.path.exists(buildPath):
            subprocess.call('mkdir '+buildPath, shell=True)
        else:
            subprocess.call('rm -r '+buildPath, shell=True)
        cmd = 'xcodebuild -exportArchive -exportOptionsPlist '+path+'/'+name+'/info.plist'+' -archivePath '+archievePath+' -exportPath '+buildPath
        subprocess.call(cmd, shell=True)
        return buildPath+'/'+name+'.ipa'


    # 获取当前时间的字符串
    def __dateStr(self):
        timeStr = time.strftime('%F-%T')
        return timeStr

